package com.lancoo.znbkxx.teacher.ui.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.github.mikephil.charting.components.LimitLine
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.AnswerSkillAdapter
import com.lancoo.znbkxx.teacher.adapter.SpacesItemDecoration
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.databinding.FmtSkillcommentBinding
import com.lancoo.znbkxx.teacher.model.data.AnswerSkillCom
import com.lancoo.znbkxx.teacher.ui.activity.AnswerSkillCommentActivity
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.viewmodel.HardSolutionViewModel
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener

import kotlinx.android.synthetic.main.fmt_skillcomment.*


/**
 *@author Admin
 *@date 2021/2/24
 *
 */
class SkillCommentFragment : BaseVMFragment<HardSolutionViewModel, FmtSkillcommentBinding>(),
        BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener {
    private val skillList = mutableListOf<AnswerSkillCom>()
    private lateinit var skillAdapter: AnswerSkillAdapter
    private val barEntries = mutableListOf<BarEntry>() //X轴文本 与barEntries 长度一致
    private val xLabels = mutableListOf<String>() //柱子文本 与barEntries 长度一致
    private var pageSize = 10
    private var totalCount = 0

    override fun setLayoutID(): Int {
        return R.layout.fmt_skillcomment
    }

    override fun providerContext(): Any {
        return this
    }

    override fun providerVMClass(): Class<HardSolutionViewModel>? {
        return HardSolutionViewModel::class.java
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        tv_title.typeface = Typeface.createFromAsset(requireContext().assets,
                "fonts/cool_black.TTF")
        initSkillList()
    }

    private fun initSkillList() {
        val manager = LinearLayoutManager(requireContext())
        rv_skill.layoutManager = manager
        skillAdapter = AnswerSkillAdapter(skillList)
        skillAdapter.setHeaderFooterEmpty(false, true)
        val emptyView = layoutInflater.inflate(R.layout.empty_view, null)
        skillAdapter.emptyView = emptyView
        skillAdapter.onItemChildClickListener = this
        skillAdapter.onItemClickListener = this
        val map = hashMapOf<String, Int>()
        map[SpacesItemDecoration.TOP_SPACE] = DensityUtils.dp2px(requireContext(), 5f)
        map[SpacesItemDecoration.BOTTOM_SPACE] = DensityUtils.dp2px(requireContext(), 5f)
        val itemDecoration = SpacesItemDecoration(map)
        rv_skill.addItemDecoration(itemDecoration)
        rv_skill.adapter = skillAdapter
        swipe_layout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageSize = 10
                getSkillList()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (totalCount >= pageSize) {
                    pageSize += 10
                    getSkillList()
                }
            }
        })
    }

    override fun startObserve() {
        viewModel.answerSkill.observe(this, Observer {
            xLabels.clear()
            barEntries.clear()
            totalCount = it.RecommendTypeCount
            tv_recommend.text = HtmlUtils.setText(
                    getString(R.string.recommend_type, it.RecommendTypeCount.toString()))
            skillList.clear()
            skillList.addAll(it.RecommendType)
            skillAdapter.setNewData(skillList)
            swipe_layout.finishRefresh()
            swipe_layout.setEnableLoadMore(pageSize < it.RecommendTypeCount)
            if (pageSize == it.RecommendTypeCount) {
                swipe_layout.finishLoadMoreWithNoMoreData()
            } else {
                swipe_layout.finishLoadMore()
            }
            skillList.forEachIndexed { index, item ->
                val barEntry = BarEntry(index.toFloat(), item.LossRate.toFloat(), item.IsComment)
                barEntries.add(barEntry)
                val type = if (item.GenreName.isNotEmpty()) item.GenreName else item.TypeName
                xLabels.add(type)
            }
            if (it.TypeList.isNotEmpty()) {
                initChart(it.WarnRate)
            } else {
                textView22.visibility = View.GONE
                tv_lost_percent.visibility = View.GONE
            }
        })
    }

    private fun initChart(warnRate: String) {
        val xAxis: XAxis = chart.xAxis
        chart.apply {
            val barDataSet = MyBarDataSet(barEntries, "")
            barDataSet.colors = mutableListOf(Color.parseColor("#ffd234"),
                    Color.parseColor("#2dbcff"))
            val barData = BarData(barDataSet)
            barData.setDrawValues(false) //是否显示柱子的数值
            val widthScale = if (barEntries.size >= 5) 1f else barEntries.size.toFloat() / 5
            barData.barWidth = 8f / 25f * widthScale //每个柱子的宽度
            chart.data = barData
            axisLeft.apply {
                isEnabled = true
                setDrawGridLines(false)
                setDrawAxisLine(false)
                setDrawLabels(false)
                spaceBottom = 0f
                axisMinimum = 0f
                axisMaximum = 1f
            }
            axisRight.isEnabled = false
            axisLeft.addLimitLine(LimitLine(0.6f))
            //关闭图例
            legend.isEnabled = false
            //关闭描述信息的显示
            description.isEnabled = false
            //打开缩放交互
            setPinchZoom(false)
            setScaleEnabled(false)
            isClickable = false
            //设置x轴显示在下方
            xAxis.isEnabled = true
            xAxis.mAxisMinimum = -0.5f
            xAxis.mAxisMaximum = 7f
            xAxis.position = XAxis.XAxisPosition.BOTTOM
            xAxis.isGranularityEnabled = true
            xAxis.granularity = 1f
            xAxis.labelCount = xLabels.size
            //设置X轴文本旋转角度
            xAxis.labelRotationAngle = 0f
            xAxis.setDrawLabels(true)
            xAxis.setDrawAxisLine(false)
            xAxis.setDrawGridLines(false)
            //设置X轴文本大小
            xAxis.textSize = 10f
            xAxis.textColor = Color.parseColor("#98aece")
            xAxis.valueFormatter = IndexAxisValueFormatter(xLabels) //设置x轴标签格式化器
            setVisibleXRangeMaximum(5f)
            chart.animateY(1000)
        }
    }


    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        startActivity(Intent(requireContext(), AnswerSkillCommentActivity::class.java).apply {
            putExtra("typeName", skillList[position].TypeName)
            putExtra("typeNo", skillList[position].TypeNo)
            putExtra("genreID", skillList[position].GenreID)
        })
    }

    @SuppressLint("SetTextI18n")
    override fun onResume() {
        super.onResume()
        tv_stuname.text = "${Ext.STU_NAME}的各题型失分率统计"
        getSkillList()
    }

    private fun getSkillList() {
        viewModel.getAnswerSkill(Ext.STU_ID, 1, pageSize)
    }
}